<?php

namespace Admin\Savers;

/**
 * Description of Saver
 *
 * @author nofear
 */
class Saver {

    private $EntityManager;
    private $request;

    public function __construct() {
        $this->EntityManager = \Shared\Application::getInstance()->getEntityManager();
        $this->request = \Shared\Application::getInstance()->getRequest();
    }

    public function process($Object) {
        $this->EntityManager->persist($Object);
    }

    public function commit() {
        $this->EntityManager->flush();
    }

    public function saveMultimedia($Object) {
        $countarray = count($_FILES['pictures']['name']);
        $newarray = array();
        for ($i = 0; $i < $countarray; $i++) {
            if ($_FILES['pictures']['size'][$i]) {
                $newarray[$i]['picture']['name'] = $_FILES['pictures']['name'][$i];
                $newarray[$i]['picture']['type'] = $_FILES['pictures']['type'][$i];
                $newarray[$i]['picture']['tmp_name'] = $_FILES['pictures']['tmp_name'][$i];
                $newarray[$i]['picture']['error'] = $_FILES['pictures']['error'][$i];
                $newarray[$i]['picture']['size'] = $_FILES['pictures']['size'][$i];
            }
        }

        if (!empty($newarray)) {
            foreach ($newarray as $_FILES) {
                $temp = explode(".", $_FILES["picture"]["name"]);
                $md5 = md5(file_get_contents($_FILES["picture"]["tmp_name"]));

                $File = $this->EntityManager->getRepository('Shared\Multimedia\File')->findOneByMd5($md5);

                if (!$File) {
                    if (isset($temp[1]) && in_array($temp[1], array('jpg', 'jpeg', 'png', 'gif'))) {
                        list($width, $height) = getimagesize($_FILES["picture"]["tmp_name"]);

                        $File = new \Shared\Multimedia\Image();
                        $File->setWidth($width);
                        $File->setHeight($height);
                    } else if (isset($temp[1]) && in_array($temp[1], array('txt', 'doc'))) {
                        $File = new \Shared\Multimedia\Document();
                    } else {
                        throw new Exception('Invalid file type');
                    }

                    $File->setName($temp[0]);
                    $File->setExt($temp[1]);
                    $File->setMd5($md5);
                } else if ($File instanceof \Shared\Multimedia\Image) {
//                    $QB = $this->EntityManager->createQueryBuilder();
//
//                    $QB->update('Shared\Multimedia\SiteObjectGalleryItem', 'sogi')
//                            ->set('sogi.isMain', '0')
//                            ->set('sogi.isActive', '0')
//                            ->where('sogi.SiteObject = :SiteObject')
//                            ->setParameter('SiteObject', $Object->getId())
//                            ->getQuery()
//                            ->execute();
                }
                $QB = $this->EntityManager->createQueryBuilder();

//                $QB->update('Shared\Multimedia\SiteObjectGalleryItem', 'sogi')
//                        ->set('sogi.isMain', '0')
//                        ->set('sogi.isActive', '0')
//                        ->where('sogi.SiteObject = :SiteObject')
//                        ->setParameter('SiteObject', $Object->getId())
//                        ->getQuery()
//                        ->execute();

                $this->EntityManager->persist($File);

                $SiteObjectFile = new \Shared\Multimedia\SiteObjectGalleryItem;

                $SiteObjectFile->setFile($File);
                $SiteObjectFile->setSiteObject($Object);
                $SiteObjectFile->setIsActive(true);
                $SiteObjectFile->setIsMain(true);

                $this->EntityManager->persist($Object);
                $this->EntityManager->persist($SiteObjectFile);
                $this->EntityManager->flush();

                if ((($_FILES["picture"]["type"] == "image/gif") || ($_FILES["picture"]["type"] == "image/jpeg") || ($_FILES["picture"]["type"] == "image/jpg") || ($_FILES["picture"]["type"] == "image/pjpeg") || ($_FILES["picture"]["type"] == "image/x-png") || ($_FILES["picture"]["type"] == "image/png"))) {
                    if ($_FILES["picture"]["error"] > 0) {
                        echo "Error: " . $_FILES["picture"]["error"] . "<br>";
                        exit;
                    } else {
                        if (file_exists("img/" . $_FILES["picture"]["name"])) {
                            echo $_FILES["picture"]["name"] . " already exists. ";
                        } else {
                            $path = \Shared\Application::getInstance()->getFilesDir();
//                            $path = ROOT_DIR . 'data' . DS . 'files';
                            if (!file_exists($path)) {
                                mkdir($path);
                            }
                            $split = str_split($File->getId());
                            while (list ($key, $val) = each($split)) {
                                $path .= DIRECTORY_SEPARATOR . $val;
                                if (!file_exists($path)) {
                                    mkdir($path);
                                }
                            }
                            move_uploaded_file($_FILES["picture"]["tmp_name"], $path . DIRECTORY_SEPARATOR . $File->getId());
                        }
                    }
                } else if (!$_FILES["picture"]) {
                    echo "Invalid file";
                    exit;
                }
            }
        }

        $mmItems = $this->request->get('mmItems');

        if (count($mmItems)) {
            foreach ($mmItems as $id => $itemData) {
                $SOGI = $this->EntityManager->find('Shared\Multimedia\SiteObjectGalleryItem', (int) $id);

                if ($SOGI) {
                    $SOGI->setTitle($itemData['title']);
                    $SOGI->setDescription($itemData['description']);

                    $this->EntityManager->persist($SOGI);
                }
            }

            $this->EntityManager->flush();
        }
    }

    public function saveMetadata($Object) {
        $metaDescription = $this->sanitize($this->request->get('metaDescription'));
        $metaTagNames = explode(',', $this->request->get('as_values_tags'));
        $Metadata = $Object->getMetaData() ? : new \Shared\Main\Metadata;
        $Metadata->setDescription($metaDescription);
        $TagsCollection = $Metadata->getTags();
        $TagsCollection->clear();

        if (count($metaTagNames)) {
            foreach ($metaTagNames as $metaTagName) {
                if ($metaTagName) {
                    $Tag = $this->EntityManager->getRepository('Shared\Main\Tag')->findOneByName($metaTagName);

                    if (!$Tag) {
                        $Tag = new \Shared\Main\Tag;
                        $Tag->setName($metaTagName);
                        $this->process($Tag);
                    }

                    $TagsCollection->add($Tag);
                }
            }
        }

        $this->process($Metadata);
        return $Metadata;
    }

    public function sanitize($str, $type = 'string') {
        switch ($type) {
            case 'email':
                $filter = FILTER_SANITIZE_EMAIL;
                break;
            case 'float':
                $filter = FILTER_SANITIZE_NUMBER_FLOAT;
                break;
            case 'int':
                $filter = FILTER_SANITIZE_NUMBER_INT;
                break;
            default:
                $filter = FILTER_SANITIZE_STRING;
                break;
        }

        $str = filter_var(trim($str), $filter);

        return $str;
    }

}
